package com.artconcurrency.chapter2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName com.artconcurrency.chapter2
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019/5/1 13:36
 * @Version 1.0
 */
public class Counter {
    private int i = 0;
    private AtomicInteger atomicInt = new AtomicInteger(0);
    public static void main(String[] args) {
        int size = 600;
        final Counter cas = new Counter();
        List<Thread> ts = new ArrayList<>(size);
        long start = System.currentTimeMillis();
        for (int i = 0; i < size; i++) {
            Thread t = new Thread(()->{
                cas.count();
                cas.safeCount();
            });
            ts.add(t);
        }
        for (Thread t :ts) {
            t.start();
        }

        //等待所有线程执行完成
        for (Thread t: ts ) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(cas.i);
        System.out.println(cas.atomicInt.get());
        System.out.println(System.currentTimeMillis()-start);

    }

    /**
     * 使用CAS实现线程安全计数器
     */
    private void safeCount(){
        for (;;){
            int i = atomicInt.get();
            //cas 对比
            boolean flag = atomicInt.compareAndSet(i,i++);
            if(flag){
                atomicInt.incrementAndGet();
                break;
            }
        }
    }

    /**
     * 非线程安全计数器
     */
    private void count(){
        i++;
    }
}
